import React, { useCallback, useEffect, useState } from 'react';
import Context from './context';
import useBasisCash from '../../hooks/useBasisCash';
import { VoteInfo } from '../../basis-cash/types';
import config, { voteDefinitions } from '../../config';
import { ethers } from 'ethers';

const Votes: React.FC = ({ children }) => {
  const [votes, setVotes] = useState<VoteInfo[]>([]);
  const basisCash = useBasisCash();

  const fetchPools = useCallback(async () => {
    const votes: VoteInfo[] = [];
    console.log('voteDefinitions', voteDefinitions);
    for (const voteInfo of Object.values(voteDefinitions)) {
      console.log('voteInfo.contract', voteInfo.contract);
      voteInfo.starttime = Number(ethers.utils.formatUnits(await basisCash.contracts['proposal'].startTime(), 18));
      voteInfo.endtime = Number(ethers.utils.formatUnits(await basisCash.contracts['proposal'].endTime(), 18));
      votes.push({
        ...voteInfo
      });
      console.log('voteInfo.contract', voteInfo.contract);
    }
    console.log('votes', votes);
    votes.sort((a, b) => (a.sort > b.sort ? 1 : -1));
    setVotes(votes);
  }, [basisCash, basisCash?.isUnlocked, setVotes]);

  useEffect(() => {
    if (basisCash) {
      fetchPools()
        .catch(err => console.error(`Failed to fetch pools: ${err.stack}`));
    }
  }, [basisCash, basisCash?.isUnlocked, fetchPools]);

  return <Context.Provider value={{ votes }}>{children}</Context.Provider>;
};

export default Votes;
